using Microsoft.Office.Core;
using Microsoft.Office.Interop.PowerPoint;
using System;
using System.Diagnostics;
using System.IO;
using Shape = Microsoft.Office.Interop.PowerPoint.Shape;

namespace ppt2imgWin
{
	public class OperatePPT
	{
		private string imgDir;

		private Application objApp;

		private Presentation objPresSet;

		public void ExportSlide(int slidesCount, Slide s, int maxAnimationOrder)
		{
			s.Export(string.Concat(new object[]
			{
				this.imgDir,
				s.SlideIndex,
				"_",
				maxAnimationOrder + 1,
				"_.jpg"
			}), "jpg", 0, 0);
			s.SlideShowTransition.Hidden = MsoTriState.msoFalse;
			for (int i = maxAnimationOrder; i >= 1; i--)
			{
				for (int j = s.Shapes.Count; j > 0; j--)
				{
					if (s.Shapes[j].AnimationSettings.Animate == MsoTriState.msoTrue && s.Shapes[j].AnimationSettings.AnimationOrder == i)
					{
						s.Shapes[j].Delete();
						s.Export(string.Concat(new object[]
						{
							this.imgDir,
							s.SlideIndex,
							"_",
							i,
							".jpg"
						}), "jpg", 0, 0);
					}
				}
			}
		}

		public string ExportToImg(string filePath, string imgDir)
		{
			string result = "";
			this.imgDir = imgDir;
			try
			{
				if (!Directory.Exists(this.imgDir))
				{
					Directory.CreateDirectory(this.imgDir);
				}
				if (this.objApp == null)
				{
					this.objApp = (Application)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("91493441-5A91-11CF-8700-00AA0060263B")));
					this.objPresSet = this.objApp.Presentations.Open(filePath, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
				//	this.objApp.Assistant.On = false;
					this.objApp.DisplayAlerts = PpAlertLevel.ppAlertsNone;
					int pptpagecount = this.objPresSet.Slides.Count;
					for (int i = 1; i <= pptpagecount; i++)
					{
						Slide slide = this.objPresSet.Slides[i];
						int max = this.GetAnimationMaxOrder(slide);
						this.ExportSlide(this.objPresSet.Slides.Count, slide, max);
					}
				}
			}
			catch (Exception arg_E5_0)
			{
				result = arg_E5_0.ToString();
				EventLog.WriteEntry("ppt2img", arg_E5_0.ToString(), EventLogEntryType.Error);
			}
			finally
			{
				this.objPresSet.Saved = MsoTriState.msoTrue;
				this.objPresSet.Close();
				this.objApp.Quit();
			}
			return result;
		}

		public int GetAnimationMaxOrder(Slide slide)
		{
			slide.SlideShowTransition.Hidden = MsoTriState.msoTrue;
			int max = 0;
			foreach (Shape shape in slide.Shapes)
			{
				if (shape.AnimationSettings.Animate == MsoTriState.msoTrue && shape.AnimationSettings.AnimationOrder > max)
				{
					max = shape.AnimationSettings.AnimationOrder;
				}
			}
			return max;
		}
	}
}
